from django.shortcuts import render
from .models import Topic
from django.http import HttpResponseRedirect
from django.urls import reverse
from .forms import TopicForm

def index(request):
    '''学习笔记的主页'''
    return render(request, 'logs/index.html')
    # return HttpResponse('学习笔记主页')

def topics(request):
    '''显示所有主题'''
    topics = Topic.objects.order_by('date_added')
    context = {'topics':topics}
    return render(request, 'logs/topics.html', context)

def topic(request, topic_id):
    '''显示单个主题以及其所有条目'''
    topic = Topic.objects.get(id=topic_id)
    entries = topic.entry_set.oder_by('-date_added')
    context = {'topic':topic,'entries':entries}
    return render(request, 'logs/topic.html', context)

def new_topic(request):
    '''添加新主题'''
    if request.method != 'POST':
        # 未提交数据：创建一个新表单
        form = TopicForm()

    else:
        # POST提交的数据，对数据进行处理
        form = TopicForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('logs:topics'))

    context = {'form':form}
    return render(request,'logs/new_topic.html', context)

# Create your views here.
